﻿#include "page5.h"
#include <databaseManager.h>
#include <QMessageBox>
#include <QBarSeries>
#include <QBarSet>
#include <QDate>
#include <QBarCategoryAxis>
#include <QValueAxis>
#include <QLineSeries>
// #include <QDebug>
#include <QtCharts/QChartView>

Page5::Page5(QWidget *parent) :
    QWidget(parent),
    mainLayout(new QVBoxLayout(this)),
    chartView(nullptr)
{
    // 设置窗口大小
    setFixedSize(1280, 720);
    //设置背景
    QPixmap background(":new/prefix1/bg.jpg");
    QLabel* backgroundLabel = new QLabel(this);
    backgroundLabel->setPixmap(background.scaled(this->size())); // 缩放背景图片以适应窗口大小

    backgroundLabel->setGeometry(0, 0, this->width(), this->height());
    backgroundLabel->lower();

    // 设置按钮的初始Y轴位置
    int yPos = 222;

    // Assuming you have a QIcon object created from your image file
    QIcon icon1(":new/prefix1/order.jpg");
    QIcon icon11(":new/prefix1/order2.jpg");
    // Create the QPushButton and set its properties
    orderButton = new QPushButton(this);
    orderButton->setIcon(icon1);  // Set the icon
    orderButton->setIconSize(QSize(260, 71));  // Set the icon size
    orderButton->setFlat(true);  // Make the button flat (no background)
    orderButton->setFixedSize(260, 71);  // Set the fixed size of the button
    orderButton->setGeometry(1, yPos, 260, 71);
    connect(orderButton, &QPushButton::clicked, this, [this](){
        emit orderRequested();
    });
    connect(orderButton, &QPushButton::pressed, this, [this, icon11]() {
        orderButton->setIcon(icon11);  // Change to icon10 when pressed
    });

    connect(orderButton, &QPushButton::released, this, [this, icon1]() {
        orderButton->setIcon(icon1);  // Revert to icon1 when released
        emit orderRequested();  // Emit the signal after the button is released
    });

    // 调整下一个按钮的Y轴位置
    yPos += 68;

    // 创建并设置生产按钮
    QIcon icon2(":new/prefix1/production.jpg");
    QIcon icon12(":new/prefix1/production2.jpg");
    productionButton = new QPushButton("", this);
    productionButton->setIcon(icon2);  // Set the icon
    productionButton->setIconSize(QSize(260, 71));  // Set the icon size
    productionButton->setFlat(true);  // Make the button flat (no background)
    productionButton->setFixedSize(260, 71);  // Set the fixed size of the button
    productionButton->setGeometry(1, yPos, 260, 71);
    connect(productionButton, &QPushButton::clicked, this, [this]() {
        emit productionRequested();
    });
    connect(productionButton, &QPushButton::pressed, this, [this, icon12]() {
        productionButton->setIcon(icon12);
    });

    connect(productionButton, &QPushButton::released, this, [this, icon2]() {
        productionButton->setIcon(icon2);
        emit productionRequested();  // Emit the signal after the button is released
    });

    // 调整下一个按钮的Y轴位置
    yPos += 68;

    // 创建并设置财务按钮
    QIcon icon3(":new/prefix1/finance.jpg");
    QIcon icon13(":new/prefix1/finance2.jpg");
    financeButton = new QPushButton("", this);
    financeButton->setIcon(icon13);  // Set the icon
    financeButton->setIconSize(QSize(260, 71));  // Set the icon size
    financeButton->setFlat(true);  // Make the button flat (no background)
    financeButton->setFixedSize(260, 71);  // Set the fixed size of the button
    financeButton->setGeometry(1, yPos, 260, 71);
    connect(financeButton, &QPushButton::clicked, this, [this]() {
        emit financeRequested();
    });
    connect(financeButton, &QPushButton::pressed, this, [this, icon3]() {
        financeButton->setIcon(icon3);
    });

    connect(financeButton, &QPushButton::released, this, [this, icon13]() {
        financeButton->setIcon(icon13);
        emit financeRequested();  // Emit the signal after the button is released
    });

    // 调整下一个按钮的Y轴位置
    yPos += 68;

    // 创建并设置库存按钮
    QIcon icon4(":new/prefix1/warehouse.jpg");
    QIcon icon14(":new/prefix1/warehouse2.jpg");
    warehouseButton = new QPushButton("", this);
    warehouseButton->setIcon(icon4);  // Set the icon
    warehouseButton->setIconSize(QSize(260, 71));  // Set the icon size
    warehouseButton->setFlat(true);  // Make the button flat (no background)
    warehouseButton->setFixedSize(260, 71);  // Set the fixed size of the button
    warehouseButton->setGeometry(1, yPos, 260, 71);
    connect(warehouseButton, &QPushButton::clicked, this, [this]() {
        emit storeRequested();
    });
    connect(warehouseButton, &QPushButton::pressed, this, [this, icon14]() {
        warehouseButton->setIcon(icon14);
    });

    connect(warehouseButton, &QPushButton::released, this, [this, icon4]() {
        warehouseButton->setIcon(icon4);
        emit storeRequested();  // Emit the signal after the button is released
    });

    creditingButton = new QPushButton(u8"", this);
    creditingButton->setGeometry(265,60,264,75); // 调整此位置以适应屏幕
    creditingButton->setStyleSheet("QPushButton {"
                                   " border: none; "
                                   "background-image: url(:new/prefix1/shouzhibiao.jpg); "
                                   "background-repeat: no-repeat; "
                                   "background-position: center; }");
    connect(creditingButton, &QPushButton::pressed, this, [this]() {
        creditingButton->setStyleSheet("QPushButton {"
                                       " border: none; "
                                       "background-image: url(:/new/prefix1/shouzhibiao2.jpg); "
                                       "background-repeat: no-repeat; "
                                       "background-position: center; }");
    });

    // Connect released signal to change the background image back to shouzhibiao.jpg
    connect(creditingButton, &QPushButton::released, this, [this]() {
        creditingButton->setStyleSheet("QPushButton {"
                                       " border: none; "
                                       "background-image: url(:/new/prefix1/shouzhibiao.jpg); "
                                       "background-repeat: no-repeat; "
                                       "background-position: center; }");
    });

    spendButton = new QPushButton(u8"", this);
    spendButton->setGeometry(530,60,264,75); // 调整此位置以适应屏幕
    spendButton->setStyleSheet("QPushButton {"
                               " border: none; "
                               "background-image: url(:new/prefix1/tianjiashoukuan.jpg); "
                               "background-repeat: no-repeat; "
                               "background-position: center; }");
    connect(spendButton, &QPushButton::pressed, this, [this]() {
        spendButton->setStyleSheet("QPushButton {"
                                   " border: none; "
                                   "background-image: url(:/new/prefix1/tianjiashoukuan2.jpg); "
                                   "background-repeat: no-repeat; "
                                   "background-position: center; }");
    });


    connect(spendButton, &QPushButton::released, this, [this]() {
        spendButton->setStyleSheet("QPushButton {"
                                   " border: none; "
                                   "background-image: url(:/new/prefix1/tianjiashoukuan.jpg); "
                                   "background-repeat: no-repeat; "
                                   "background-position: center; }");
    });



    connect(creditingButton, &QPushButton::clicked, this, [this]() {
        emit pageRequested11();
    });


    connect(spendButton, &QPushButton::clicked, this, [this]() {
        Page5::openFinanceDialog();
    });

    // 创建返回按钮
        frontButton = new QPushButton(u8"", this);
        frontButton->setGeometry(1050,0,170,55); // 调整此位置以适应屏幕
        frontButton->setStyleSheet("QPushButton {"
                                 " border: none; "
                                 "background-image: url(:new/prefix1/tuichudenglu.jpg); "
                                 "background-repeat: no-repeat; "
                                 "background-position: center; }");


        connect(frontButton, &QPushButton::pressed, this, [this]() {
            frontButton->setStyleSheet("QPushButton {"
                                     " border: none; "
                                     "background-image: url(:/new/prefix1/tuichudenglu2.jpg); "
                                     "background-repeat: no-repeat; "
                                     "background-position: center; }");
        });
        connect(frontButton, &QPushButton::released, this, [this]() {
            frontButton->setStyleSheet("QPushButton {"
                                     " border: none; "
                                     "background-image: url(:/new/prefix1/tuichudenglu.jpg); "
                                     "background-repeat: no-repeat; "
                                     "background-position: center; }");
        });

   connect(frontButton, &QPushButton::clicked, this, &Page5::onFrontButtonClicked);
   QVBoxLayout* backLayout = new QVBoxLayout(this);
   setLayout(backLayout);

    yPos += 68;
    //用户指南
    QIcon icon6(":new/prefix1/operationGuide.jpg");
    QIcon icon16(":new/prefix1/operationGuide2.jpg");
    helpButton = new QPushButton("", this);
    helpButton->setIcon(icon6);  // Set the icon
    helpButton->setIconSize(QSize(260, 71));  // Set the icon size
    helpButton->setFlat(true);  // Make the button flat (no background)
    helpButton->setFixedSize(260, 71);  // Set the fixed size of the button
    helpButton->setGeometry(1, yPos, 260, 71);

    connect(helpButton, &QPushButton::clicked, this, [this]() {
        emit pageRequested10();
    });

    connect(helpButton, &QPushButton::pressed, this, [this, icon16]() {
        helpButton->setIcon(icon16);
    });
    connect(helpButton, &QPushButton::released, this, [this, icon6]() {
        helpButton->setIcon(icon6);
        emit pageRequested10();  // Emit the signal after the button is released
    });

    //连接按钮
         yPos += 68;
        QIcon icon7(":new/prefix1/connect.jpg");
        QIcon icon17(":new/prefix1/connect2.jpg");
        connectButton = new QPushButton("", this);
        connectButton->setIcon(icon7);  // Set the icon
        connectButton->setIconSize(QSize(260, 71));  // Set the icon size
        connectButton->setFlat(true);  // Make the button flat (no background)
        connectButton->setFixedSize(260, 71);  // Set the fixed size of the button
        connectButton->setGeometry(1, yPos, 260, 71);

        connect(connectButton, &QPushButton::clicked, this, [this]() {
            emit pageRequested13();
        });

        yPos += 68;

        // 创建并设置添加员工按钮
        QIcon icon5(":new/prefix1/tianjiayuangong01.jpg");
        QIcon icon15(":new/prefix1/tianjiayuangong02.jpg");
        addEmployeeButton = new QPushButton("", this);
        addEmployeeButton->setIcon(icon5);  // Set the icon
        addEmployeeButton->setIconSize(QSize(260, 71));  // Set the icon size
        addEmployeeButton->setFlat(true);  // Make the button flat (no background)
        addEmployeeButton->setFixedSize(260, 71);  // Set the fixed size of the button
        addEmployeeButton->setGeometry(1, yPos, 260, 71);
        connect(addEmployeeButton, &QPushButton::clicked, this, [this]() {
            emit addEmployeeRequested();
        });




        connect(connectButton, &QPushButton::pressed, this, [this, icon17]() {
             connectButton->setIcon(icon17);
        });
        connect(connectButton, &QPushButton::released, this, [this, icon7]() {
            connectButton->setIcon(icon7);
            emit pageRequested13();  // Emit the signal after the button is released
        });



    setLayout(mainLayout);
}
void Page5::financeHide()
{
    // 隐藏财务按钮
    financeButton->hide();
}
void Page5::openFinanceDialog()
{
    FinanceDialog dialog(this);
    if (dialog.exec() == QDialog::Accepted) {
        QString type = "尾款";
        QString date = dialog.getDate()->date().toString("yyyy-MM-dd");
        int id = dialog.getId()->text().toInt();
        int amount = dialog.getAmount()->text().toInt();

        QList<int> lastTotals = DatabaseManager::instance().getFinanceLastTotal();
        int totalIncome = lastTotals[0] + amount;
        int totalOutcome = lastTotals[1];
        int totalInterest = totalIncome - totalOutcome;

        if (DatabaseManager::instance().insertFinanceRecord(id, type, date, amount, totalIncome, totalOutcome, totalInterest)) {
            QMessageBox::information(this, u8"成功", u8"订单已成功添加到数据库");

            if (!DatabaseManager::instance().markPurchaseOrderAsCompleted(id)) {
                QMessageBox::warning(this, u8"警告", u8"无法将订单状态标记为已完成");
            }
        } else {
            QMessageBox::warning(this, u8"警告", u8"无法插入财务记录");
        }
    }
}

void Page5::clearOldChart()
{
    if (chartView) {
        mainLayout->removeWidget(chartView);
        delete chartView;
        chartView = nullptr;
    }
}

int Page5::getQuarter(const QString &dateStr) {
    QDate date = QDate::fromString(dateStr, "yyyy-MM-dd");
    return (date.month() - 1) / 3 + 1;
}

void Page5::processFinanceData(const QList<QList<QVariant>> &records,
                               QMap<int, double> &totalIncome,
                               QMap<int, double> &totalExpense)
{
    for (const auto &record : records) {
        QString recordType = record[0].toString();
        int quarter = getQuarter(record[1].toString());
        double amount = record[2].toDouble();

        if (recordType == "首款" || recordType == "尾款") {
            totalIncome[quarter] += amount;
        } else if (recordType == "支出") {
            totalExpense[quarter] += amount;
        }
    }
}

void Page5::generateQuarterlyReport()
{
    clearOldChart();

    // 从数据库获取数据
    DatabaseManager &dbManager = DatabaseManager::instance();
    QList<QList<QVariant>> records = dbManager.getFinanceRecordsForLinePlot();

    // 数据处理
    QMap<int, double> totalIncome, totalExpense, profit, profitRate;
    processFinanceData(records, totalIncome, totalExpense);

    for (int quarter : totalExpense.keys()) {
        profit[quarter] = totalIncome[quarter] - totalExpense[quarter];
        if (totalExpense[quarter] != 0) {
            profitRate[quarter] = (profit[quarter] / totalExpense[quarter]) * 100; // 转换为百分比
        } else {
            profitRate[quarter] = 0;
        }
    }

    // 创建图表
    QChart *chart = new QChart();

    // 创建柱状图系列
    QBarSet *setIncome = new QBarSet("总收入");
    QBarSet *setExpense = new QBarSet("总支出");
    QBarSet *setProfit = new QBarSet("利润");
    for (int i = 1; i <= 4; ++i) {
        *setIncome << totalIncome[i];
        *setExpense << totalExpense[i];
        *setProfit << profit[i];
    }

    QBarSeries *barSeries = new QBarSeries();
    barSeries->append(setIncome);
    barSeries->append(setExpense);
    barSeries->append(setProfit);
    chart->addSeries(barSeries);

    // 创建折线图系列
    QLineSeries *lineSeriesPositiveProfitRate = new QLineSeries();
    lineSeriesPositiveProfitRate->setName("正利润率");
    lineSeriesPositiveProfitRate->setColor(Qt::red);

    QLineSeries *lineSeriesNegativeProfitRate = new QLineSeries();
    lineSeriesNegativeProfitRate->setName("负利润率");
    lineSeriesNegativeProfitRate->setColor(Qt::green);

    for (int i = 1; i <= 4; ++i) {
        if (profitRate[i] >= 0) {
            lineSeriesPositiveProfitRate->append(i - 1, profitRate[i]); // 利润率已经转换为百分比
            lineSeriesNegativeProfitRate->append(i - 1, 0); // 保证负利润率曲线与正利润率曲线对齐
        } else {
            lineSeriesPositiveProfitRate->append(i - 1, 0); // 保证正利润率曲线与负利润率曲线对齐
            lineSeriesNegativeProfitRate->append(i - 1, profitRate[i]);
        }
    }

    chart->addSeries(lineSeriesPositiveProfitRate);
    chart->addSeries(lineSeriesNegativeProfitRate);

    // 设置轴
    QBarCategoryAxis *axisX = new QBarCategoryAxis();
    axisX->append(QStringList() << "第一季度" << "第二季度" << "第三季度" << "第四季度");
    chart->addAxis(axisX, Qt::AlignBottom);
    barSeries->attachAxis(axisX);
    lineSeriesPositiveProfitRate->attachAxis(axisX);
    lineSeriesNegativeProfitRate->attachAxis(axisX);

    QValueAxis *axisY = new QValueAxis();
    axisY->setRange(0, 5000);
    axisY->setTitleText("金额");
    chart->addAxis(axisY, Qt::AlignLeft);
    barSeries->attachAxis(axisY);

    QValueAxis *axisYRight = new QValueAxis();
    axisYRight->setRange(-100, 100); // 调整范围以包括负利润率
    axisYRight->setTitleText("利润率 (%)");
    chart->addAxis(axisYRight, Qt::AlignRight);
    lineSeriesPositiveProfitRate->attachAxis(axisYRight);
    lineSeriesNegativeProfitRate->attachAxis(axisYRight);

    chart->setTitle("2024年度盈亏图");

    // 设置动画
    chart->setAnimationOptions(QChart::AllAnimations);

    // 创建图表视图
    chartView = new QChartView(chart);
    chartView->setRenderHint(QPainter::Antialiasing);

    // 设置布局
    mainLayout->setContentsMargins(265, 135, 0, 0); // 设置外边距以控制图表位置

    // 添加图表视图到布局
    mainLayout->addWidget(chartView);
}
void Page5::signuphide() {
    // 隐藏财务按钮
    addEmployeeButton->hide();
}
void Page5::onFrontButtonClicked()
{
    QMessageBox msgBox;
    msgBox.setText("确定退出登录吗?");
    msgBox. setWindowTitle("退出登录");
    msgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
    msgBox.button(QMessageBox::Ok)->setText("确认");
    msgBox.button(QMessageBox::Cancel)->setText("取消");
    msgBox.setStyleSheet(
        "QMessageBox {"
        "  background-color: #FFFFFF;"
        "}"
        "QMessageBox QLabel {"
        "  font-size: 18px;"
        "  font-weight: bold;"
        "  color: black;"
        "}"
        "QMessageBox QPushButton {"
        "  font-size: 18px;"
        "  font-weight: bold;"
        "  border: 2px solid #E0E0E0;"
        "  border-radius: 20px;"
        "  padding: 10px;"
        "  background-color: #0093D1;"
        "  color: white;"
        "}"
    );

    if (msgBox.exec() == QMessageBox::Ok) {
        emit pageRequested1();
    }
}
